package cn.ad.server.persistence;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

@Repository
public class DeviceRepositoryImpl implements DeviceRepository {

	static final Logger logger = LoggerFactory.getLogger(DeviceRepositoryImpl.class);
	
	/**
	 * 设备id前缀常量
	 */
	static final String DEVICE_KEY = "deviceid.";
	
	@Autowired
	private ConfigRepository configRepository;
	
	/**
	 * 生成用于缓存的key
	 * @param deviceid
	 * @return
	 */
	String generateDeviceCacheKey(String deviceid){
		return DEVICE_KEY+deviceid;
	}
	
	@Resource(name = "countRedisTemplate")
	private ValueOperations<String, String> deviceTemplate;
	
	@Resource(name = "countRedisTemplate")
	private RedisTemplate<String, String> redisTemplate;

	@Override
	public String fetchChannelId(String deviceid) {
		return deviceTemplate.get(generateDeviceCacheKey(deviceid));
	}
	
	@Override
	public void setChannelIdIfAbsent(String deviceid, String value) {
		long deviceIdTimeout = configRepository.fetchDeviceIdTimeout();
		String deviceCacheKey = generateDeviceCacheKey(deviceid);
		deviceTemplate.setIfAbsent(deviceCacheKey, value);
		redisTemplate.expire(deviceCacheKey, deviceIdTimeout, TimeUnit.MINUTES);
	}


	@Override
	public void setChannelId(String deviceid, String value) {
		long deviceIdTimeout = configRepository.fetchDeviceIdTimeout();
		String deviceCacheKey = generateDeviceCacheKey(deviceid);
		deviceTemplate.set(deviceCacheKey, value,deviceIdTimeout, TimeUnit.MINUTES);
	}
	
}
